//
//  YLCTrainRegisInfoViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/3/19.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCTrainRegisInfoViewController.h"
#import "YLCTrainRegisInfoCell.h"
#import "YLCTrainRegisInfoHeadView.h"
#import "YLCTrainRegisInfoFootView.h"
#import "YLCRegisPersonViewController.h"
#import "YLCActivityPayViewController.h"
#import "YLCMessageWriteViewController.h"
#define INFO_CELL @"YLCTrainRegisInfoCell"
#define INFO_HEAD @"YLCTrainRegisInfoHeadView"
#define INFO_FOOT @"YLCTrainRegisInfoFootView"
@interface YLCTrainRegisInfoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,YLCMessageWriteViewControllerDelegate>

@end

@implementation YLCTrainRegisInfoViewController
{
    UICollectionView *trainTable;
    UILabel *payLabel;
    UIButton *payBtn;
    UIButton *rightItemButton;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (UIBarButtonItem *)rightBarButtonItem{
    
    rightItemButton =  [YLCFactory createLabelBtnWithTitle:@"收藏" titleColor:[UIColor whiteColor]];
    
    rightItemButton.frame = CGRectMake(0, 0, 60, 40);
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:rightItemButton];
    
    [rightItemButton addTarget:self action:@selector(gotoCollect:) forControlEvents:UIControlEventTouchUpInside];
    
    [rightItemButton setTitle:@"已收藏" forState:UIControlStateSelected];
    
    return item;
}

- (void)gotoCollect:(UIButton *)sender{
    NSString *collectType = @"";
    if (_type==0) {
        collectType = @"3";
    }
    if (_type==1) {
        collectType = @"1";
    }
    NSString *path = @"";
    NSString *tip = @"";
    if (sender.selected) {
        path = @"app/collect/cancel";
        tip = @"取消成功";
    }else{
        path = @"app/collect/doSave";
        tip = @"收藏成功";
    }
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    [YLCNetWorking loadNetServiceWithParam:@{@"token":userModel.token,@"userId":userModel.user_id,@"type":collectType,@"relationId":_model.id} method:@"POST" urlPath:path delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            
            return ;
        }
        rightItemButton.selected = !rightItemButton.selected;
        [SVProgressHUD showSuccessWithStatus:tip];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDataSource];
    [self createCustomView];
}
- (void)initDataSource{

    if (_type==0) {
        [self loadTrainInfo];
    }else{
        [self loadActivityInfo];
    }
}
- (void)loadTrainInfo{
    
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    [YLCNetWorking loadNetServiceWithParam:@{@"trainId":_model.id,@"token":userModel.token,@"userId":userModel.user_id} method:@"POST" urlPath:@"app/train/detail" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        _model = [YLCActivityModel modelWithDict:responseObject];
        _model.hasLoad = NO;
        _model.content = [YLCFactory htmlEntityDecode:_model.content];
        [_model downLoadHTMLAttrWithComplete:^{
            [trainTable reloadData];
        }];
        rightItemButton.selected = [_model.is_collect isEqualToString:@"1"];
        NSString *payString = [NSString stringWithFormat:@"活动费用:￥%@元",_model.fee];
        
        NSMutableAttributedString *attr = [YLCFactory getThreeCountAttributedStringWithString:payString FirstCount:5 secondCount:1 thirdCount:_model.fee.length+1 firstColor:RGB(122, 128, 130) secondColor:YLC_THEME_COLOR thirdColor:YLC_THEME_COLOR firstFont:18 secondFont:13 thirdFont:21];
        
        payLabel.attributedText = attr;
        
        [self layoutPayBtnWithIsEnroll:[_model.is_enroll isEqualToString:@"1"]];
        
        [trainTable reloadData];
    }];

}
- (void)loadActivityInfo{
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    [YLCNetWorking loadNetServiceWithParam:@{@"activityId":_model.id,@"token":userModel.token,@"userId":userModel.user_id} method:@"POST" urlPath:@"app/activity/detail" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        _model = [YLCActivityModel modelWithDict:responseObject];
        rightItemButton.selected = [_model.is_collect isEqualToString:@"1"];
        NSString *payString = [NSString stringWithFormat:@"活动费用:￥%@元",_model.fee];
        
        NSMutableAttributedString *attr = [YLCFactory getThreeCountAttributedStringWithString:payString FirstCount:5 secondCount:1 thirdCount:_model.fee.length+1 firstColor:RGB(122, 128, 130) secondColor:YLC_THEME_COLOR thirdColor:YLC_THEME_COLOR firstFont:18 secondFont:13 thirdFont:21];
        
        payLabel.attributedText = attr;
        
        [self layoutPayBtnWithIsEnroll:[_model.is_enroll isEqualToString:@"1"]];
        
        [trainTable reloadData];
    }];
}
- (void)layoutPayBtnWithIsEnroll:(BOOL)isEnroll{
    if (isEnroll) {
        
        payBtn.backgroundColor = YLC_GRAY_COLOR;
        
        payBtn.enabled = NO;
        
        [payBtn setTitle:@"已报名" forState:UIControlStateNormal];
        
    }else{
        payBtn.backgroundColor = YLC_THEME_COLOR;
        
        payBtn.enabled = YES;
        
        [payBtn setTitle:@"我要报名" forState:UIControlStateNormal];
    }

}
- (void)createCustomView{
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    flow.minimumLineSpacing = 10;
    
    trainTable = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    
    trainTable.backgroundColor = YLC_COMMON_BACKCOLOR;
    
    [trainTable registerClass:[YLCTrainRegisInfoCell class] forCellWithReuseIdentifier:INFO_CELL];
    
    [trainTable registerClass:[YLCTrainRegisInfoHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:INFO_HEAD];
    
    [trainTable registerClass:[YLCTrainRegisInfoFootView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:INFO_FOOT];
    
    trainTable.delegate = self;
    
    trainTable.dataSource = self;
    
    [self.view addSubview:trainTable];
    
    [trainTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectZero];
    
    bottomView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:bottomView];
    
    WS(weakSelf)
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.view.mas_bottom);
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.height.equalTo(50);
    }];
    
    payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    payBtn.backgroundColor = YLC_THEME_COLOR;
    
    [payBtn setTitle:@"我要报名" forState:UIControlStateNormal];
    
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [payBtn addTarget:self action:@selector(gotoJoin) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView addSubview:payBtn];
    
    payLabel = [YLCFactory createLabelWithFont:17 color:YLC_THEME_COLOR];
    
    [bottomView addSubview:payLabel];
    
    [payLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView.mas_left).offset(15);
        make.centerY.equalTo(bottomView.mas_centerY);
    }];
    
    [payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView.mas_right);
        make.centerY.equalTo(bottomView.mas_centerY);
        make.width.equalTo(100);
        make.height.equalTo(50);
    }];
}
- (void)gotoJoin{
    if (_type==0) {
        [self gotoTrain];
    }else{
        [self payActivity];
    }
}
- (void)gotoTrain{
    YLCMessageWriteViewController *con = [[YLCMessageWriteViewController alloc] init];
    
    con.type = 0;
    
    con.activityId = _model.id;
    
    con.delegate = self;
    
    [self.navigationController pushViewController:con animated:YES];
}
- (void)payActivity{
    
    YLCMessageWriteViewController *con = [[YLCMessageWriteViewController alloc] init];
    
    con.type = 1;
    
    con.activityId = _model.id;
    
    con.delegate = self;
    
    [self.navigationController pushViewController:con animated:YES];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YLCTrainRegisInfoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:INFO_CELL forIndexPath:indexPath];
    
    cell.model = _model;
    
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind==UICollectionElementKindSectionHeader) {
        YLCTrainRegisInfoHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:INFO_HEAD forIndexPath:indexPath];
        
        
        headView.model = _model;
        
        return headView;
    }
    if (kind==UICollectionElementKindSectionFooter) {
        YLCTrainRegisInfoFootView *footView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:INFO_FOOT forIndexPath:indexPath];
        
        footView.model = _model;
        
        footView.type = _type;
        
        return footView;
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_model.hasLoad) {
        CGRect rect = [_model.htmlAttr boundingRectWithSize:CGSizeMake(self.view.frameWidth-20, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
        
        return CGSizeMake(self.view.frameWidth, 70+rect.size.height);
    }
//    CGSize size = [YLCFactory getStringSizeWithString:_model.content width:self.view.frameWidth-20 font:15];
    return CGSizeMake(self.view.frameWidth, 70);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(self.view.frameWidth, 290);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(self.view.frameWidth, 120);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 0, 10, 0);
}
- (void)didFinishJoin{
    [self initDataSource];
    [self layoutPayBtnWithIsEnroll:YES];
}
- (NSString *)title{
    return @"活动详情";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
